package com.xiaoniu.forum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoniu.forum.common.constant.ForumConstant;
import com.xiaoniu.forum.dao.MemberDao;
import com.xiaoniu.forum.entity.MemberEntity;
import com.xiaoniu.forum.form.PhoneLoginForm;
import com.xiaoniu.forum.form.PhoneRegisterForm;
import com.xiaoniu.forum.form.UsernamePasswordLoginForm;
import com.xiaoniu.forum.form.UsernamePasswordResgisterForm;
import com.xiaoniu.forum.renren.common.exception.RRException;
import com.xiaoniu.forum.service.AppLoginService;
import com.xiaoniu.forum.service.AppRegisterService;
import com.xiaoniu.forum.service.MemberService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.UUID;

@Service
public class AppRegisterServiceImpl implements AppRegisterService {

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private AppLoginService loginService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public void phoneRegister(PhoneRegisterForm form) {
        if (queryByKeyValue("phone",form.getMobile()) != null){
            throw new RRException("手机号已注册,请登录");
        }

        //判断手机验证码
        String redisKey = "MSM:" + form.getMobile();
        String code = (String) redisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isEmpty(code)||!StringUtils.pathEquals(code,form.getCaptcha())){
            throw new RRException("验证码错误,请正确输入!");
        }

        MemberEntity member=new MemberEntity();
        member.setPhone(form.getMobile());
        member.setUsername(form.getMobile()); //设置账号为手机号，避免其他用户使用该手机号作为用户名注册
        member.setPassword(DigestUtils.sha256Hex(form.getPassword()));
        member.setStatus(ForumConstant.TRUE);
        member.setOfficial(ForumConstant.FALSE);
        member.setAvatar(ForumConstant.DEFAULT_USER_AVATAR);
        member.setNickname("用户"+ UUID.randomUUID().toString().substring(0,8));
        memberDao.insert(member);

    }

    @Override
    public void usernamePasswordRegister(UsernamePasswordResgisterForm form) {
        if (queryByKeyValue("username",form.getUsername()) != null){
            throw new RRException("用户名已注册,请登录");
        }
        MemberEntity member=new MemberEntity();
        member.setUsername(form.getUsername());
        member.setPassword(DigestUtils.sha256Hex(form.getPassword()));
        member.setStatus(ForumConstant.TRUE);
        member.setOfficial(ForumConstant.FALSE);
        memberDao.insert(member);
    }

    private MemberEntity queryByKeyValue(String key,Object value){
        return memberDao.selectOne(new QueryWrapper<MemberEntity>().eq(key,value));
    }
}
